import {
  commands,
  Event,
  EventEmitter,
  ExtensionContext,
  ProviderResult,
  TreeDataProvider,
} from 'vscode';
import { CommandConst } from '../../../constants';
import { api } from '../../../service';
import { SystemListItem } from '../system-list-item/system-list-item';

type EvtType = void | IData | null | undefined;

/**
 * 当前用户系统列表
 *
 * @author chitanda
 * @date 2022-12-13 10:12:56
 * @export
 * @class SystemListProvider
 * @implements {TreeDataProvider<IData>}
 */
export class SystemListProvider implements TreeDataProvider<IData> {
  readonly evt: EventEmitter<EvtType> = new EventEmitter<EvtType>();

  onDidChangeTreeData: Event<EvtType> = this.evt.event;

  /**
   * 是否为第一次，第一次的时候默认预加载一次。其余按照事件触发，加载数据
   *
   * @author chitanda
   * @date 2021-12-15 14:12:44
   * @protected
   */
  protected first = true;

  protected items: IData[] = [];

  constructor(protected context: ExtensionContext) {
    this.init();
  }

  protected init(): void {
    this.initCommand();
  }

  protected initCommand(): void {
    // 刷新系统列表
    commands.registerCommand(
      CommandConst.SYSTEM.LIST.REFRESH,
      this.refresh,
      this,
    );
  }

  /**
   * 刷新任务
   *
   * @author chitanda
   * @date 2021-12-14 10:12:13
   * @protected
   * @return {*}  {Promise<void>}
   */
  protected async refresh(): Promise<void> {
    await this.load();
    this.evt.fire(undefined);
  }

  protected timer?: NodeJS.Timeout;

  /**
   * 加载任务信息
   *
   * @author chitanda
   * @date 2021-12-14 10:12:41
   * @protected
   * @return {*}  {Promise<IPSData[]>}
   */
  protected load(): Promise<IData[]> {
    return new Promise(resolve => {
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = undefined;
      }
      this.timer = setTimeout(async () => {
        this.first = false;
        const items = await api.system.fetch();
        this.items = items.sort((a, b) => {
          if (a.ordervalue > b.ordervalue) {
            return 1;
          }
          return -1;
        });
        resolve(this.items);
      }, 200);
    });
  }

  async getTreeItem(data: IData): Promise<SystemListItem> {
    const treeItem = new SystemListItem(data);
    return treeItem;
  }

  async getChildren(): Promise<IData[]> {
    if (this.first) {
      await this.refresh();
    }
    return this.items;
  }

  getParent(_element: IData): ProviderResult<IData> {
    return undefined;
  }
}
